/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "subprocess.h"
#include "../../common/debug.h"

int z_subprocess_spawn_sync(char **args)
{
    pid_t pid;
    int rv = 0;

    pid = fork();
    if (pid)
    {
        wait(&rv);
        return rv;
    }
    else
    {
        int e = execvp(args[0], args);
        if (e != 0)
            Z_WARNING("subprocess did not spawn correctly: %s", args[0]);
        _exit(0);
    }

    return 0;
}

int z_subprocess_spawn_async(char **args)
{
    pid_t pid;

    pid = fork();
    if (pid)
    {
        return pid;
    }
    else
    {
        int e = execvp(args[0], args);
        if (e != 0)
            Z_WARNING("subprocess did not spawn correctly: %s", args[0]);
        _exit(0);
    }

    return 0;
}

int z_subprocess_spawn_async_redirect(char **args)
{
    pid_t pid;
    int p2c[2];
    int c2p[2];

    pipe(p2c);
    pipe(c2p);

    pid = fork();
    if (pid)
    {
        dup2(p2c[1], 1);
        close(p2c[0]);
        dup2(c2p[0], 0);
        close(c2p[1]);
        setvbuf(stdout, (char *)NULL, _IONBF, 0);
        return pid;
    }
    else
    {
        dup2(p2c[0], 0);
        close(p2c[1]);
        dup2(c2p[1], 1);
        close(c2p[0]);
        setvbuf(stdout, (char *)NULL, _IONBF, 0);
        close(2);
        dup2(1, 2);
        int e = execvp(args[0], args);
        if (e != 0)
            Z_WARNING("subprocess did not spawn correctly: %s", args[0]);
        _exit(0);
    }

    return 0;
}

int z_subprocess_wait(int pid)
{
    int rv = 0;
    waitpid(pid, &rv, WUNTRACED|WCONTINUED);
    return rv;
}
